package com.grm.sys.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grm.sys.entity.SysMenu;
import com.grm.sys.service.mapper.SysMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统菜单服务
 *
 * @author gaorimao
 * @date 2022/02/08
 */
@Slf4j
@Service
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    public List<SysMenu> queryMenusByUserId(Long userId) {
        return sysMenuMapper.queryMenusByUserId(userId);
    }

    /**
     * 构建树
     *
     * @param menuList 菜单列表
     * @return {@link List}<{@link SysMenu}>
     */
    public List<SysMenu> buildTree(List<SysMenu> menuList) {
        List<SysMenu> treeMenus = new ArrayList<>();
        List<SysMenu> rootNodes = getRootNode(menuList);
        for (SysMenu childTree : rootNodes) {
            childTree = buildChildTree(childTree, menuList);
            treeMenus.add(childTree);
        }
        return treeMenus;
    }

    /**
     * 构建子树
     *
     * @param pNode    p节点
     * @param menuList 菜单列表
     * @return {@link SysMenu}
     */
    private SysMenu buildChildTree(SysMenu pNode, List<SysMenu> menuList) {
        List<SysMenu> childMenus = new ArrayList<>();
        for (SysMenu menuNode : menuList) {
            if (menuNode.getParentId().equals(pNode.getId())) {
                childMenus.add(buildChildTree(menuNode, menuList));
            }
        }
        pNode.setChildren(childMenus);
        return pNode;
    }

    /**
     * 获取根节点
     *
     * @param menuList 菜单列表
     * @return {@link List}<{@link SysMenu}>
     */
    private List<SysMenu> getRootNode(List<SysMenu> menuList) {
        List<SysMenu> rootMenuLists = new ArrayList<>();
        for (SysMenu menuNode : menuList) {
            if (menuNode.getParentId() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}
